package com.btkjgc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.btkjgc.models.AdminUser;
import com.btkjgc.models.email.EmailResult;
import com.btkjgc.service.impl.AdminUserManageService_Impl;
import com.btkjgc.service.impl.AdminUserService_Impl;
import com.btkjgc.service.impl.LeftBarManager_Impl;
import com.btkjgc.service.impl.RoleFunctionService_Impl;
import com.btkjgc.service.intf.AdminUserManageService_Intf;
import com.btkjgc.utils.Constant;
import com.btkjgc.utils.FtlOperationUtil;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.SendEmail;

/**
 * Created by Administrator on 14-3-6.
 */
@Controller
public class LoginController
{

	Logger logger = Logger.getLogger(LoginController.class);

	Map<Integer, Integer> rootIndexMap;// 用来记录该index对应的root节点

	AdminUserService_Impl adminUserService = new AdminUserService_Impl();
	AdminUserManageService_Intf adminUserManageService = new AdminUserManageService_Impl();

	RoleFunctionService_Impl roleFunctionService = new RoleFunctionService_Impl();

	// 忘记密码，通过邮箱找回密码
	@RequestMapping(value = { "/login/forgetpw" })
	public ModelAndView forgetPW(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		String username = request.getParameter("username");
		// 若username = null表明还未设置要找回密码的账号
		if (username == null) { return new ModelAndView("login"); }
		// 如果已经设置了要找回密码的账号
		AdminUser adminUser = adminUserService.getAdminByName(username);
		EmailResult result = new EmailResult();
		if (adminUser == null)
		{// 账号不存在
			result.setResult(Constant.SEND_ADMIN_NOT_EXIST);
		}
		else
		{
			if (FtlOperationUtil.isNull(adminUser.getEmail())
					|| !SendEmail.isEmailFormat(adminUser.getEmail()))
			{// 邮箱不合法
				result.setResult(Constant.SEND_EMAIL_NOT_LEGAL);
			}
			else
			{
				try
				{
					result.setResult(Constant.SEND_SUCCESS);
					result.setContent(adminUser.getEmail());
					adminUser.setPw_retrieve_time(""
							+ System.currentTimeMillis());
					adminUserService.updateAdmin(adminUser);
					SendEmail.pwRetrieveByEmail(adminUser.getEmail(), username,
							adminUser.getPw_retrieve_time());// 发送邮件
				}
				catch (Exception e)
				{
					result.setResult(Constant.SEND_ERROR);
					e.printStackTrace();
				}
			}
		}

		// 设置输出的编码格式
		response.setCharacterEncoding("utf-8");
		PrintWriter printer = response.getWriter();
		printer.print(JSON.toJSONString(result));
		printer.flush();
		printer.close();
		return null;
	}

	// 重设密码（邮箱链接处理）
	@RequestMapping(value = { "/login/pwretrieve" })
	public ModelAndView pwRetrieve(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 需要加上id加密设置
		String username = request.getParameter("user");
		if (!FtlOperationUtil.isNull(username))
		{
			String id = request.getParameter("id");
			AdminUser admin = adminUserService.getAdminByName(username);
			if (!FtlOperationUtil.isNull(admin.getPw_retrieve_time()))
			{
				long duration = System.currentTimeMillis()
						- Long.parseLong(admin.getPw_retrieve_time());
				duration = duration / 1000 / 60;// 分钟
				String code = admin.getPw_retrieve_time();
				if (duration <= 30 && id.equals(code))
				{// 验证码
					ModelAndView mv = new ModelAndView("pwretrieve");
					mv.addObject("username", username);
					return mv;
				}
			}
			ModelAndView mv = new ModelAndView("pw_retrieve_result");
			mv.addObject("url", Constant.ABSOLUTE_URL + "login");
			return mv;
		}
		return new ModelAndView("redirect:/login");
	}

	// 重设密码（邮箱找回）
	@RequestMapping(value = { "/login/pwreset" })
	public ModelAndView pwReset(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 需要加上id加密设置
		String username = request.getParameter("username");
		if (!FtlOperationUtil.isNull(username))
		{// 重设密码
			String pw = request.getParameter("password");
			adminUserManageService.changePWByName(username, pw);
			ModelAndView mv = new ModelAndView("pw_retrieve_result");
			mv.addObject("result", "success");
			;
			mv.addObject("url", Constant.ABSOLUTE_URL + "login");
			return mv;
		}
		return new ModelAndView("pwretrieve");
	}

	// 获取登陆页面，跳转到登陆页面login.ftl
	@RequestMapping(value = { "login" }, method = { RequestMethod.GET })
	public ModelAndView getLoginPage(HttpServletRequest request)
	{
		AdminUser usr = (AdminUser) request.getSession().getAttribute("user");
		String url = request.getRequestURL().toString();
		Constant.ABSOLUTE_URL = url.substring(0, url.length() - 5);
		if (usr != null)
		{
			int roleId = roleFunctionService.getRoleId(usr.getId());
			ModelAndView mv;
			if (roleId == 1)
			{
				mv = new ModelAndView("redirect:/car_map");
			}
			else
			{
				mv = new ModelAndView("redirect:/index");
			}
			return mv;
		}
		else
		{
			ModelAndView mv = new ModelAndView("login");

			Boolean alreadyLogin = (Boolean) request.getSession().getAttribute(
					"alreadyLogin");
			if (alreadyLogin != null && alreadyLogin)
			{
				mv.addObject("alreadyLogin", true);
			}
			return mv;
		}
	}

	// 实现用户登陆操作，跳转到后台管理程序首页index.ftl
	@RequestMapping(value = "do_login", method = { RequestMethod.POST })
	public ModelAndView doLogin(
			HttpServletRequest request,
			@RequestParam(value = "user_name", required = true) String username,
			@RequestParam(value = "passwords", required = true) String password)
	{
		// 从数据库取出这一行
		AdminUser adminUser = adminUserService.getAdminByName(username);
		if (adminUser != null
				&& adminUser.getPassword().equals(DigestUtils.md5Hex(password)))
		{
			// 登录成功，更新上次登录的ip地址
			String lastIp = request.getRemoteAddr();
			adminUserService.updateLastLoginTp(adminUser.getId(), lastIp);
			// adminUser.setLastip(lastIp);

			int roleId = roleFunctionService.getRoleId(adminUser.getId());
			// Rong 登录成功，取出登陆者信息

			adminUser.setRoleId(roleId);
			request.getSession().setAttribute("user", adminUser);
 
			// 修改上次登录时间和登录次数
			// 先获取时间
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			String loginTime = df.format(new Date());// new Date()为获取当前系统时间
			// 获取username的id(主键)
			String userID = adminUser.getId() + "";
			String hqlUpdateLastLoginTime = "update AdminUser set lastlogin =?, logintimes =logintimes + 1 where id=?";
			String[] parameter = { loginTime, userID };
			HibernateUtil.executeUpdate(hqlUpdateLastLoginTime, parameter);

			Map<String, Map<String, Boolean>> roleFunction = roleFunctionService
					.getRoleFunction(roleId);
			if (roleFunction != null && roleFunction.size() > 0)
				request.getSession()
						.setAttribute("role_function", roleFunction);
			request.getSession().setAttribute("role_id", roleId);
			request.getSession().setAttribute("role_level",
					roleFunctionService.getRoleLevel(roleId));

			request.getSession().setAttribute("left_menu",
					(new LeftBarManager_Impl()).getLeftMenuByRoleId(roleId));
			request.getSession().setAttribute("rootIndexMap", rootIndexMap);
			ModelAndView mv = null;
			if (roleId == 1)
			{
				mv = new ModelAndView("redirect:/car_map");
			}
			else
			{
				mv = new ModelAndView("redirect:/index");
			}
			return mv;
		}
		else
		{
			ModelAndView mv = new ModelAndView("login");
			mv.addObject("wrongpw", "wrongpw");
			mv.addObject("user_name", username);
			return mv;
		}
	}

	// 实现用户注销操作，跳转到登陆页面login.ftl
	@RequestMapping(value = "do_logout", method = { RequestMethod.GET })
	public ModelAndView doLogout(HttpServletRequest request)
	{
		request.getSession().invalidate();
		ModelAndView mv = new ModelAndView("login");
		return mv;
	}

	@RequestMapping(value = "changepw", method = { RequestMethod.GET })
	public @ResponseBody
	String changeUserPW(HttpServletRequest request,
			@RequestParam(value = "pwd", required = true) String changePW0)
	{
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute(
				"user");
		AdminUserManageService_Impl temp = new AdminUserManageService_Impl();
		String pw = changePW0;
		String str = "";
		if (pw != null && pw != "")
		{
			temp.changePWById(adminUser.getId(), pw);
			str = "Success change PW";
		}
		else
		{
			str = "Failed change PW";
		}
		return '"' + str + '"';
	}

}
